import base64
import pickle
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    """
    登录后将cookie中的购物车信息合并到redis中
    :param request: 本次请求对象获取cookie中的信息
    :param user:  获取登录后的信息
    :param response: 本次响应对象,clear cookie信息
    :return: response
    """

    # 获取cookie中的carts
    cookie_carts = request.COOKIES.get('carts')

    # 判断是否存在carts
    if not cookie_carts:
        return response

    # 存在后提取出cookie_carts中的字典
    dict_carts = pickle.loads(base64.b64decode(cookie_carts.encode()))
    print(dict_carts)

    new_cart_dict = {}
    new_cart_selected_add = []
    new_cart_selected_rem = []
    for sku_id, cookie_dict in dict_carts.items():
        new_cart_dict[sku_id] = cookie_dict['count']
        if cookie_dict['selected']:
            new_cart_selected_add.append(sku_id)
        else:
            new_cart_selected_rem.append(sku_id)
    # 连接redis
    redis_conn = get_redis_connection('carts')

    # 将new_cart 写入redis中
    pl = redis_conn.pipeline()
    # 用于同时将多个 field-value (字段-值)对设置到哈希表中。此命令会覆盖哈希表中已存在的字段。如果哈希表不存在，会创建一个空哈希表
    pl.hmset('carts_%s' % user.id, new_cart_dict)

    if new_cart_selected_add:
        pl.sadd('selected_%s' % user.id, *new_cart_selected_add)
    elif new_cart_selected_rem:
        pl.srem('selected_%s' % user.id, *new_cart_selected_rem)

    pl.execute()

    response.delete_cookie('carts')
    return response
